package me.shurufa.activities;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.Bind;
import cn.finalteam.okhttpfinal.HttpRequest;
import me.shurufa.R;
import me.shurufa.bean.Catalog;
import me.shurufa.bean.Excerpt;
import me.shurufa.model.AddDigestBean;
import me.shurufa.model.CameraModel;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.CatalogListResp;
import me.shurufa.response.base.BaseResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;
import me.shurufa.widget.popupwindow.WheelPopWindow;

/**
 * 作者 : andy
 * 日期 : 16/3/14 14:19
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 选择章节归属
 */
public class SelectCatalogActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.left_text)
    TextView leftText;

    @Bind(R.id.right_image)
    ImageView rightImage;

    @Bind(R.id.right_text)
    TextView rightText;

    @Bind(R.id.ll_have_chapter)
    LinearLayout ll_have_chapter;

    @Bind(R.id.ll_no_chapter)
    LinearLayout ll_no_chapter;

    // 有目录
    @Bind(R.id.tv_select_catalog)
    TextView tv_select_catalog;

    // 无目录
    @Bind(R.id.btn_tell_need_chapter)
    Button btn_tell_need_chapter;

    @Bind(R.id.btn_jump_finish)
    Button btn_jump_finish;

    private WheelPopWindow wheelPopWindow;
    private AddDigestBean mAddDigestBean;
    private List<Catalog> mCatalogs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_select_chapter;
        super.onCreate(savedInstanceState);
        parseArguments();
        initUI();
    }

    public static void initArguments(Intent in, AddDigestBean addDigestBean) {
        in.putExtra(Constants.ARG_ADD_DIGEST, addDigestBean);
    }

    private void parseArguments() {
        if (getIntent() != null) {
            mAddDigestBean = (AddDigestBean) getIntent().getSerializableExtra(Constants.ARG_ADD_DIGEST);
        }
    }

    private void initUI() {
        rightText.setText(getString(R.string.complete));
        rightImage.setVisibility(View.GONE);
        rightText.setVisibility(View.VISIBLE);
        rightText.setOnClickListener(this);
        if (null != titleTextView) {
            titleTextView.setText(R.string.chapter_affiliation);
        }

        initListener();
        initData();
    }

    private void initListener() {
        tv_select_catalog.setOnClickListener(this);
        btn_jump_finish.setOnClickListener(this);
        btn_tell_need_chapter.setOnClickListener(this);
    }

    private void initData() {

        try {
            // 若是继续添加
            if (CameraModel.mAddDigestBean != null) {
                if (CameraModel.mAddDigestBean.excerptedBookId == mAddDigestBean.excerptedBookId) {
                    tv_select_catalog.setText(CameraModel.mAddDigestBean.chapterName);
                    mAddDigestBean.menuId = CameraModel.mAddDigestBean.menuId;
                    reqCatalogs(false, false);
                } else {
                    reqCatalogs(true, true);
                }
            } else {
                reqCatalogs(true, true);
            }
        } catch (Exception e) {
            reqCatalogs(true, true);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_text:
                onNext();
                break;
            case R.id.tv_select_catalog:
                showSelectCatalogWheelView();
                break;
            case R.id.btn_jump_finish:
                jumpFinish();
                break;
            case R.id.btn_tell_need_chapter:
                reqNeedCatalog();
                break;
        }
    }

    /**
     * 请求提交需要目录
     */
    private void reqNeedCatalog() {
        try {
            String book_id = mAddDigestBean.chapterBookId;
            RequestParams params = new RequestParams();
            params.addFormDataPart("book_id", book_id);
            HttpRequest.post(API.NEED_CATELOG, params, new HttpCallback<BaseResp>(this) {
                @Override
                public void onRespSuccess(BaseResp resp) {
                    Utils.showToast(getString(R.string.thks_feedback));
                }

                @Override
                public void onRespFailure(BaseResp resp) {

                }
            });
        } catch (Exception e) {
        }

    }

    /**
     * 直接完成
     */
    private void jumpFinish() {
        onNext();
    }

    /**
     * 打开滚轮控件 选择章节
     */
    private void showSelectCatalogWheelView() {
        wheelPopWindow = new WheelPopWindow(this, mCatalogs);
        wheelPopWindow.showPickerWindow(tv_select_catalog, 0);
        wheelPopWindow.setOnCompleteClickListener(new WheelPopWindow.OnCompleteClickListener() {
            @Override
            public void onCompleteClicked() {
                try {
                    Catalog selectedCatalog = wheelPopWindow.getCurrentData();
                    tv_select_catalog.setText(selectedCatalog.title);
                    mAddDigestBean.menuId = Long.parseLong(selectedCatalog.id);
                    mAddDigestBean.chapterName = selectedCatalog.title;
                    wheelPopWindow.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onItemSelected() {
                try {
                    Catalog selectedCatalog = wheelPopWindow.getCurrentData();
                    tv_select_catalog.setText(selectedCatalog.title);
                    mAddDigestBean.menuId = (selectedCatalog.id == null) ? 0l : Long.parseLong(selectedCatalog.id);
                    mAddDigestBean.chapterName = selectedCatalog.title;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 右上角点击创建书摘，  请求创建，成功则跳到下一界面
     */
    private void onNext() {
        reqCreateExcerpt();
        //reqCreateDigest();
    }

    private void reqCatalogs(final boolean showWheel, final boolean setFirstData) {

        RequestParams params = new RequestParams();
        params.addFormDataPart("id", mAddDigestBean.chapterBookId);
        HttpRequest.post(API.GET_BOOK_MENU, params, new HttpCallback<CatalogListResp>(this, getString(R.string.list_footer_loading)) {
            @Override
            public void onRespSuccess(CatalogListResp resp) {
                try {
                    //没有更多数据 不能加载更多
                    if (Utils.isNullForList(resp.data)) {
                        ll_no_chapter.setVisibility(View.VISIBLE);
                        ll_have_chapter.setVisibility(View.GONE);
                    } else {
                        ll_no_chapter.setVisibility(View.GONE);
                        ll_have_chapter.setVisibility(View.VISIBLE);
                        mCatalogs = resp.data;
                        if (showWheel) {
                            showSelectCatalogWheelView();
                        }

                        if (setFirstData && !Utils.isNullForList(resp.data)) {
                            // 默认选中第一个
                            Catalog selectedCatalog = resp.data.get(0);
                            tv_select_catalog.setText(selectedCatalog.title);
                            mAddDigestBean.menuId = Long.parseLong(selectedCatalog.id);
                            mAddDigestBean.chapterName = selectedCatalog.title;
                        }
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(CatalogListResp resp) {

            }
        });


    }

    /*private void reqCatalogs(final boolean showWheel, final boolean setFirstData) {
        new RequestServerTask<CatalogListResponse>(CatalogListResponse.class, this, getString(R.string.list_footer_loading)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("bookId", mAddDigestBean.chapterBookId);
                return HttpUtil.post(API.GET_BOOK_MENU, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onSuccess(CatalogListResponse result) {
                //没有更多数据 不能加载更多
                if (result.data == null || result.data.length == 0) {
                    ll_no_chapter.setVisibility(View.VISIBLE);
                    ll_have_chapter.setVisibility(View.GONE);
                } else {
                    ll_no_chapter.setVisibility(View.GONE);
                    ll_have_chapter.setVisibility(View.VISIBLE);
                    mCatalogs = Arrays.asList(result.data);
                    if (showWheel) {
                        showSelectCatalogWheelView();
                    }

                    if (setFirstData) {
                        // 默认选中第一个
                        Catalog selectedCatalog = wheelPopWindow.getCurrentData();
                        tv_select_catalog.setText(selectedCatalog.title);
                        mAddDigestBean.menuId = selectedCatalog.id;
                        mAddDigestBean.chapterName = selectedCatalog.title;
                    }
                }
            }
        }.start();
    }*/

    /**
     * 创建新书摘 新版
     */
    private void reqCreateExcerpt() {
        final String bookId = mAddDigestBean.chapterBookId;
        final long menuId = mAddDigestBean.menuId;
        final long notebookId = mAddDigestBean.excerptedBookId;
        final String content = mAddDigestBean.content;
        final String pageNumber = mAddDigestBean.pageNumber;
        final String note = mAddDigestBean.note;
        final String publishState = mAddDigestBean.publishState;
        final String screenShot = mAddDigestBean.screenShot;
        final int type = mAddDigestBean.type;

        // 本地使用 非上传字段
        final boolean isTextMode = Constants.DIGEST_TYPE_TEXT == mAddDigestBean.type;

        RequestParams params = new RequestParams();
        params.addFormDataPart("book_id", bookId);
        params.addFormDataPart("content", isTextMode ? content : "");
        params.addFormDataPart("page_num", pageNumber);
        params.addFormDataPart("menu_id", menuId);
        params.addFormDataPart("publish_state", publishState);
        params.addFormDataPart("notebook_id", notebookId);
        params.addFormDataPart("screen_shot", isTextMode ? "" : screenShot);
        params.addFormDataPart("type", type);
        params.addFormDataPart("note", note);

        HttpRequest.post(API.CREATE_NEW_EXCERPT, params, new HttpCallback<BaseResp>() {

            @Override
            public void onRespSuccess(BaseResp baseResp) {
                try {
                    // 创建成功
                    Utils.showToast(getString(R.string.create_excerpt_success));
                    Intent in = new Intent(SelectCatalogActivity.this, CompleteAddDigestActivity.class);
                    CompleteAddDigestActivity.initArguments(in, mAddDigestBean);
                    startActivity(in);
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(BaseResp baseResp) {

            }
        });
    }

    /**
     * 请求添加书摘
     */
    /*private void reqCreateDigest() {

        final String bookId = mAddDigestBean.chapterBookId;
        final long menuId = mAddDigestBean.menuId;
        final long notebookId = mAddDigestBean.excerptedBookId;
        final String content = mAddDigestBean.content;
        final String pageNumber = mAddDigestBean.pageNumber;
        final String note = mAddDigestBean.note;
        final String publishState = mAddDigestBean.publishState;
        final String screenShot = mAddDigestBean.screenShot;
        final int type = mAddDigestBean.type;

        // 本地使用 非上传字段
        final boolean isTextMode = Constants.DIGEST_TYPE_TEXT == mAddDigestBean.type;

        new RequestServerTask<BaseResponse>(BaseResponse.class, this, getString(R.string.waiting_creating)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("bookId", bookId);
                params.put("menuId", menuId);
                params.put("notebookId", notebookId);
                params.put("content", isTextMode ? content : "");
                params.put("screenShot", isTextMode ? "" : screenShot);
                params.put("type", type);
                params.put("pageNumber", pageNumber);
                params.put("note", note);
                params.put("publishState", publishState);
                return HttpUtil.post(API.CREATE_DIGEST, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                // 创建成功
                Utils.showToast("成功创建一条书摘");
                Intent in = new Intent(SelectCatalogActivity.this, CompleteAddDigestActivity.class);
                CompleteAddDigestActivity.initArguments(in, mAddDigestBean);
                startActivity(in);
            }
        }.start();
    }*/

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (Constants.EVENT_COMPLETE_ADD_DIGEST.equals(intent.getAction())) {
            finish();
        }
    }
}
